import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

// 通过 createAsyncThunk 创建异步动作创建函数
// actonType 前缀
//    后续会有个三个状态分别拼接到这个前缀后面
//    'book/fetchData/pending'
//    'book/fetchData/fulfilled'
//    'book/fetchData/rejected'
const typePrefix = "book/fetchData";
export const bookFetchData = createAsyncThunk(typePrefix, async () => {
  const resp = await fetch("http://localhost:3000/books").then((response) =>
    response.json()
  );
  console.log("resp", resp); // [{}, {}]
  // 需要将数据 return 出去，给到后续的 普通动作 中的 payload 参数
  return resp;
  // return Promise.reject("我错了");
});

// 调用的返回值是一个异步动作，该异步动作可以传递给 dispatch 去执行.
// 默认情况下，dispatch() 是只支持普通动作。但是RTK是集成了 redux-thunk 在里面的，所以 dispatch 也支持 异步动作了。
// console.log("bookFetchData", bookFetchData());

const bookSlice = createSlice({
  name: "book",

  initialState: {
    loading: false,
    items: [] as { id: number; name: string }[],
  },

  reducers: {},

  extraReducers: (builder) =>
    builder
      .addCase(bookFetchData.pending, (state) => {
        state.loading = true;
      })
      .addCase(bookFetchData.fulfilled, (state, { payload }) => {
        state.items = payload;
        state.loading = false;
      })
      .addCase(bookFetchData.rejected, (state) => {
        state.loading = false;
      }),

  // 监控动作
  // extraReducers: {
  //   [bookFetchData.pending](state) {
  //     console.log("pending");
  //     state.loading = true;
  //   },

  //   [bookFetchData.fulfilled](state, { payload }) {
  //     console.log("fulfilled payload", payload);
  //     state.items = payload;
  //     state.loading = false;
  //   },

  //   [bookFetchData.rejected](state) {
  //     console.log("rejected");
  //     state.loading = false;
  //   },
  // },
});

export default bookSlice.reducer;
